-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
49 lines (40 loc) · 1.18 KB
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdbool.h>
#define MAX 100
void dfs(int graph[MAX][MAX], int visited[MAX], int vertices, int current) {
visited[current] = 1;
printf("%d ", current);
for (int i = 0; i < vertices; i++) {
if (graph[current][i] == 1 && !visited[i]) {
dfs(graph, visited, vertices, i);
}
}
}
void findConnectedComponents(int graph[MAX][MAX], int vertices) {
int visited[MAX] = {0};
int component = 0;
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
component++;
printf("Component %d: ", component);
dfs(graph, visited, vertices, i);
printf("\n");
}
}
}
int main() {
int vertices, edges;
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &vertices, &edges);
int graph[MAX][MAX] = {0};
printf("Enter the edges (u v):\n");
for (int i = 0; i < edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
graph[u][v] = 1;
graph[v][u] = 1; // Because the graph is undirected
}
printf("Connected components of the graph are:\n");
findConnectedComponents(graph, vertices);
return 0;
}